package com.atguigu.yygh.msm.controller;

import com.alibaba.fastjson.JSONException;
import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.msm.config.ConstantPropertiesUtils;
import com.atguigu.yygh.msm.util.RandomUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/msm")
@Slf4j
public class MsmApiController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送手机验证码
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        try {
            code = RandomUtil.getSixBitRandom();
            String[] params = {code}; //短信中的参数
            SmsSingleSender ssender = new SmsSingleSender(
                    ConstantPropertiesUtils.APP_ID,
                    ConstantPropertiesUtils.APP_KEY);
            // 86 中国大陆  手机号码
            log.info(ConstantPropertiesUtils.SMS_SIGN);
            SmsSingleSenderResult result = ssender.sendWithParam("86",
                    phone, ConstantPropertiesUtils.TEMPLATE_ID,
                    params, "清风半月公众号", "", "");
            System.out.println(result);
            if (result.result == 0) {
                redisTemplate.opsForValue().set(phone, code, 2, TimeUnit.MINUTES);
                return Result.ok();
            }
        } catch (HTTPException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (com.github.qcloudsms.httpclient.HTTPException e) {
            e.printStackTrace();
        }

        return Result.fail().message("发送短信失败");
    }


}
